<template>
    <el-dialog
        title="在线留言"
        :visible="props.dialogVisible"
        width="30%"
        center
        :before-close="handleClose"
        class="dialog-message"
    >
        <el-form :model="formData" :rules="rules" ref="formRef" label-width="70px">
            <el-form-item label="姓名" prop="name">
                <el-input v-model="formData.name" placeholder="请输入姓名"></el-input>
            </el-form-item>

            <el-form-item label="邮箱" prop="email">
                <el-input v-model="formData.email" placeholder="请输入邮箱"></el-input>
            </el-form-item>

            <el-form-item label="内容" prop="content">
                <el-input v-model="formData.content" type="textarea" :rows="4" placeholder="请输入内容"></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="handleClose">取消</el-button>
            <el-button type="primary" @click="submitForm" :loading="loading">提交</el-button>
        </span>
    </el-dialog>
</template>
<script setup>
import { ref, reactive, defineProps, defineEmits } from 'vue'
import { Message } from 'element-ui'

const props = defineProps({
    dialogVisible: {
        type: Boolean,
        default: false,
    },
})
const emit = defineEmits(['cancel'])

const formRef = ref(null)
const loading = ref(false)

const formData = reactive({
    name: '',
    email: '',
    content: '',
})

const rules = {
    name: [
        { required: true, message: '请输入姓名', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' },
    ],
    email: [
        { required: true, message: '请输入邮箱地址', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' },
    ],
    content: [
        { required: true, message: '请输入留言内容', trigger: 'blur' },
        { min: 5, max: 500, message: '长度在 5 到 500 个字符', trigger: 'blur' },
    ],
}

const handleClose = () => {
    emit('cancel')
}

const submitForm = async () => {
    if (!formRef.value) return

    try {
        loading.value = true
        await formRef.value.validate()

        console.log('Form submitted:', formData)

        Message.success('提交成功！')
        formRef.value.resetFields()
        emit('cancel')
    } catch (error) {
        Message.error('请检查表单填写是否正确')
    } finally {
        loading.value = false
    }
}
</script>
<style lang="scss" scoped>
.dialog-message {
    .el-button {
        color: #fff;
        background: #0d87dc;
        border-radius: 0;
        border: none;
        &:hover {
            background: #993b2f;
        }
    }
}
</style>
